/**
 * OSS 上传工具
 * 集成自动 faststart 优化
 */

import OSS from 'ali-oss';

/**
 * 上传视频到 OSS，自动触发 faststart 优化
 * @param {File} file - 视频文件
 * @param {Object} options - 上传选项
 * @returns {Promise<Object>} 上传结果
 */
export async function uploadVideoWithOptimization(file, options = {}) {
  const {
    onProgress,
    onOptimizationStart,
    onOptimizationComplete,
    waitForOptimization = true, // 是否等待优化完成
    maxWaitTime = 300000 // 最大等待时间 5 分钟
  } = options;

  // 1. 获取 OSS 上传凭证（从你的后端 API）
  const credentials = await getOSSCredentials();
  
  const client = new OSS({
    region: credentials.region,
    accessKeyId: credentials.accessKeyId,
    accessKeySecret: credentials.accessKeySecret,
    stsToken: credentials.securityToken,
    bucket: credentials.bucket
  });

  // 2. 生成文件路径
  const fileName = `videos/${Date.now()}_${file.name}`;

  // 3. 上传文件
  console.log('开始上传文件...');
  const result = await client.multipartUpload(fileName, file, {
    progress: (p) => {
      const percent = Math.floor(p * 100);
      console.log(`上传进度: ${percent}%`);
      onProgress && onProgress(percent, 'uploading');
    }
  });

  console.log('文件上传完成:', result.name);

  // 4. 如果需要等待优化完成
  if (waitForOptimization) {
    onOptimizationStart && onOptimizationStart();
    
    console.log('等待 faststart 优化...');
    const optimized = await waitForOptimizationComplete(
      client,
      fileName,
      maxWaitTime,
      (progress) => {
        onProgress && onProgress(progress, 'optimizing');
      }
    );

    if (optimized) {
      console.log('优化完成');
      onOptimizationComplete && onOptimizationComplete(true);
    } else {
      console.warn('优化超时或失败，但文件已上传');
      onOptimizationComplete && onOptimizationComplete(false);
    }
  }

  return {
    url: `https://${credentials.bucket}.${credentials.region}.aliyuncs.com/${fileName}`,
    key: fileName,
    size: file.size
  };
}

/**
 * 等待优化完成
 */
async function waitForOptimizationComplete(client, fileName, maxWaitTime, onProgress) {
  const startTime = Date.now();
  const checkInterval = 2000; // 每 2 秒检查一次
  let checks = 0;

  while (Date.now() - startTime < maxWaitTime) {
    checks++;
    
    try {
      // 检查文件的 meta 标记
      const meta = await client.head(fileName);
      
      if (meta.meta && meta.meta.faststart === 'true') {
        return true; // 优化完成
      }

      // 更新进度（估算）
      const elapsed = Date.now() - startTime;
      const progress = Math.min(95, Math.floor((elapsed / maxWaitTime) * 100));
      onProgress && onProgress(progress);

    } catch (error) {
      console.error('检查优化状态失败:', error);
    }

    // 等待下一次检查
    await new Promise(resolve => setTimeout(resolve, checkInterval));
  }

  return false; // 超时
}

/**
 * 获取 OSS 上传凭证（需要你的后端 API）
 */
async function getOSSCredentials() {
  // 这里调用你的后端 API 获取 STS 临时凭证
  const response = await fetch('/api/oss/credentials');
  return await response.json();
  
  // 返回格式示例：
  // {
  //   region: 'oss-cn-hangzhou',
  //   bucket: 'your-bucket',
  //   accessKeyId: 'STS.xxx',
  //   accessKeySecret: 'xxx',
  //   securityToken: 'xxx',
  //   expiration: '2024-01-01T00:00:00Z'
  // }
}

/**
 * 检查文件是否已优化
 */
export async function checkIfOptimized(fileName) {
  const credentials = await getOSSCredentials();
  const client = new OSS({
    region: credentials.region,
    accessKeyId: credentials.accessKeyId,
    accessKeySecret: credentials.accessKeySecret,
    stsToken: credentials.securityToken,
    bucket: credentials.bucket
  });

  try {
    const meta = await client.head(fileName);
    return meta.meta && meta.meta.faststart === 'true';
  } catch (error) {
    console.error('检查失败:', error);
    return false;
  }
}
